# -*- coding: utf-8 -*-

import sys
import os
import subprocess
import shutil

def check_python_version():
    """检查Python版本是否符合要求 (3.8.20)"""
    required_version = (3, 8, 20)
    current_version = sys.version_info[:3]
    
    print(f"当前Python版本: {current_version}")
    print(f"项目要求版本: {required_version}")
    
    if current_version != required_version:
        print(f"警告: Python版本不匹配!")
        print(f"  当前版本: {current_version}")
        print(f"  要求版本: {required_version}")
        return False
    return True

def check_dependencies():
    """检查必要的依赖是否已安装"""
    dependencies = {
        'PySide2': 'PySide2',
        'paramiko': 'paramiko', 
        'openpyxl': 'openpyxl'                           
    }
    
    missing_deps = []
    
    for dep_name, import_name in dependencies.items():
        try:
            __import__(import_name)
            print(f"{dep_name}已安装")
        except ImportError:
            print(f"缺少依赖: {dep_name}")
            missing_deps.append(dep_name)
    
    return len(missing_deps) == 0

def build_with_nuitka():
    """使用Nuitka打包程序"""
    print("\n开始使用Nuitka打包程序...")
    
    # 清理之前的构建目录
    if os.path.exists("dist_nuitka"):
        shutil.rmtree("dist_nuitka")
        print("清理旧的构建目录")
    
    # 构建Nuitka命令 - 修正打包参数
    cmd = [
        sys.executable, "-m", "nuitka",
        "--standalone",  # 独立模式
        # "--windows-console-mode=disable",  # 禁用控制台窗口
        "--windows-icon-from-ico=pic.ico",  # 程序图标
        "--output-dir=dist_nuitka",  # 输出目录
        "--follow-imports",  # 跟踪导入
        "--enable-plugin=pyside2",  # 启用PySide2插件
        "--include-data-file=pic.ico=pic.ico",  # 包含图标文件
        "--include-data-dir=config=config",  # 包含配置目录
        "--include-package=utils",  # 包含utils包
        "--include-package=ui",  # 包含ui包
        "--include-package-data=utils",  # 包含utils包的数据
        "--include-package-data=ui",  # 包含ui包的数据
        "--include-module=paramiko",  # 显式包含paramiko模块
        "--include-module=cryptography",  # 显式包含cryptography模块
        "--include-module=openpyxl",  # 显式包含openpyxl模块
        "--include-module=paramiko.transport",  # 显式包含paramiko.transport模块
        "--include-module=paramiko.sftp_client",  # 显式包含paramiko.sftp_client模块
        "--include-module=paramiko.ssh_exception",  # 显式包含paramiko.ssh_exception模块
        "--include-module=paramiko.client",  # 显式包含paramiko.client模块
        "--include-module=paramiko.sftp",  # 显式包含paramiko.sftp模块
        "--include-module=paramiko.sftp_attr",  # 显式包含paramiko.sftp_attr模块
        "--include-module=paramiko.common",  # 显式包含paramiko.common模块
        "--include-module=paramiko.message",  # 显式包含paramiko.message模块
        "--include-module=paramiko.packet",  # 显式包含paramiko.packet模块
        "--include-module=paramiko.kex_group1",  # 显式包含paramiko.kex_group1模块
        "--include-module=paramiko.kex_group14",  # 显式包含paramiko.kex_group14模块
        "--include-module=paramiko.kex_ecdh_nist",  # 显式包含paramiko.kex_ecdh_nist模块
        "--include-module=paramiko.kex_gex",  # 显式包含paramiko.kex_gex模块
        "--include-module=paramiko.compress",  # 显式包含paramiko.compress模块
        "--include-module=paramiko.buffered_pipe",  # 显式包含paramiko.buffered_pipe模块
        "--include-module=paramiko.primes",  # 显式包含paramiko.primes模块
        "--include-module=paramiko.rsakey",  # 显式包含paramiko.rsakey模块
        "--include-module=paramiko.dsskey",  # 显式包含paramiko.dsskey模块
        "--include-module=paramiko.ecdsakey",  # 显式包含paramiko.ecdsakey模块
        "--include-module=paramiko.ed25519key",  # 显式包含paramiko.ed25519key模块
        "--include-module=paramiko.sftp_handle",  # 显式包含paramiko.sftp_handle模块
        "--include-module=paramiko.sftp_server",  # 显式包含paramiko.sftp_server模块
        "--include-module=paramiko.channel",  # 显式包含paramiko.channel模块
        "--include-module=paramiko.auth_handler",  # 显式包含paramiko.auth_handler模块
        "--include-module=paramiko.agent",  # 显式包含paramiko.agent模块
        "--include-module=paramiko.win_pageant",  # 显式包含paramiko.win_pageant模块
        "--include-module=paramiko.file",  # 显式包含paramiko.file模块
        "--include-module=paramiko.pkey",  # 显式包含paramiko.pkey模块
        "--include-module=paramiko.hostkeys",  # 显式包含paramiko.hostkeys模块
        "--include-module=paramiko.server",  # 显式包含paramiko.server模块
        "--include-module=paramiko.ssh_gss",  # 显式包含paramiko.ssh_gss模块
        "--include-module=paramiko.kex_curve25519",  # 显式包含paramiko.kex_curve25519模块
        "--include-module=paramiko.kex_group16",  # 显式包含paramiko.kex_group16模块
        "--include-module=paramiko.kex_gss",  # 显式包含paramiko.kex_gss模块
        "--include-module=cryptography.hazmat",  # 显式包含cryptography.hazmat模块
        "--include-module=cryptography.hazmat.backends",  # 显式包含cryptography.hazmat.backends模块
        "--include-module=cryptography.hazmat.primitives",  # 显式包含cryptography.hazmat.primitives模块
        "--include-module=cryptography.hazmat.primitives.asymmetric",  # 显式包含cryptography.hazmat.primitives.asymmetric模块
        "--include-module=cryptography.hazmat.primitives.ciphers",  # 显式包含cryptography.hazmat.primitives.ciphers模块
        "--include-module=cryptography.hazmat.primitives.hashes",  # 显式包含cryptography.hazmat.primitives.hashes模块
        "--include-module=cryptography.hazmat.primitives.kdf",  # 显式包含cryptography.hazmat.primitives.kdf模块
        "--include-module=cryptography.hazmat.primitives.serialization",  # 显式包含cryptography.hazmat.primitives.serialization模块
        "--include-module=cryptography.hazmat.bindings",  # 显式包含cryptography.hazmat.bindings模块
        "--include-module=cryptography.hazmat.bindings.openssl",  # 显式包含cryptography.hazmat.bindings.openssl模块
        "--include-module=nacl",  # 显式包含nacl模块
        "--include-module=bcrypt",  # 显式包含bcrypt模块
        "--nofollow-import-to=tkinter",  # 排除tkinter（如果不需要）
        "--assume-yes-for-downloads",  # 自动确认下载
        "--jobs=16",  # 使用8个并行任务进行编译
        "--lto=no",  # 禁用链接时优化，可能有助于信号处理
        "--python-flag=no_site",  # 禁用site模块，减少潜在问题
        "--python-flag=no_warnings",  # 禁用警告
        #"--python-flag=ignore_environment",  # 忽略环境变量
        "main.py"  # 主程序文件
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    
    try:
        # 执行打包命令
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print("程序打包成功!")
        print("输出目录: dist_nuitka")
        return True
    except subprocess.CalledProcessError as e:
        print(f"打包失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False
    except FileNotFoundError:
        print("错误: 找不到Nuitka。请确保已安装Nuitka: pip install nuitka")
        return False

def setup_environment():
    """设置开发环境"""
    print("设置开发环境...")
    
    # 检查并安装依赖
    dependencies = ['nuitka', 'PySide2', 'paramiko', 'openpyxl']
    
    for dep in dependencies:
        try:
            __import__(dep.lower().replace('-', '_'))
            print(f"{dep} 已安装")
        except ImportError:
            print(f"正在安装 {dep}...")
            try:
                subprocess.run([sys.executable, "-m", "pip", "install", dep], check=True)
                print(f"{dep} 安装成功")
            except subprocess.CalledProcessError:
                print(f"{dep} 安装失败")
                return False
    
    return True

def main():
    """主函数"""
    print("SSH工具Nuitka打包脚本")
    print("=" * 30)
    
    # 检查是否是设置模式
    if len(sys.argv) > 1 and sys.argv[1] == '--setup':
        return setup_environment()
    
    # 检查Python版本
    if not check_python_version():
        print("\n请确保使用正确的Python版本 (3.8.20)")
        return False
    
    # 检查依赖
    if not check_dependencies():
        print("\n请安装缺失的依赖包")
        return False
    
    # 开始打包
    if build_with_nuitka():
        print("\n程序打包完成!")
        return True
    else:
        print("\n程序打包失败")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)